//
//  EPTimer.swift
//  EPHome
//
//  Created by liujianlong on 2022/9/2.
//

import UIKit

@objc open class EPTimer: NSObject {
    /// GCD定时器倒计时
    ///
    /// - Parameters:
    ///   - second: 倒计时秒数
    ///   - handler: 循环事件,闭包参数: 1.timer 2.剩余执行次数
    @objc open class func countdown(_ second: Int, _ handler: @escaping (Int) -> Void) {
        
        if second <= 0 {
            return
        }
        ///这是类方法，如果是对象方法里，timer要全局变量，下面这种方式，timer不会生效
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        var sec = second
        timer.schedule(deadline: .now(), repeating: 1)
        timer.setEventHandler {
            sec -= 1
            if  sec < 0{
                return timer.cancel()
            }
            DispatchQueue.main.async {
                handler(sec)
            }
        }
        timer.resume()
        
    }
}
